package com.example.testvolication.pojo.valid.validator;

import com.example.testvolication.pojo.dto.AnnotationClassDemo;
import com.example.testvolication.pojo.valid.annotation.ClassAllFieldCheck;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author zhangs
 * @date 2022/5/18 14:37
 */
public class ClassAllFieldCheckValidator implements ConstraintValidator<ClassAllFieldCheck , AnnotationClassDemo> {
    @Override
    public boolean isValid(AnnotationClassDemo annotationClassDemo, ConstraintValidatorContext constraintValidatorContext) {
        String name = annotationClassDemo.getName();
        boolean result = true;
        StringBuilder msgBuilder = new StringBuilder("消息提示: ");
        if (StringUtils.isEmpty(name) ||  !name.startsWith("a")){
            result = false;
            msgBuilder = msgBuilder.append(" 名称没有以a开头");
        }
        String value = annotationClassDemo.getValue();
        if (StringUtils.isEmpty(value) ||  !value.startsWith("b")){
            result = false;
            msgBuilder = msgBuilder.append(" value没有以b开头");
        }
        if (!result){
            constraintValidatorContext.disableDefaultConstraintViolation();
            constraintValidatorContext.buildConstraintViolationWithTemplate(msgBuilder.toString()).addConstraintViolation();
            return false;
        }
        return true;
    }
}
